<!-- 应用管理页面 -->
<template>
	<div id="app-manage-view">
		<!-- 搜索表单 -->
		<div class="search-section">
			<a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
				<a-form-item label="应用ID：">
					<a-input v-model:value="searchParams.id" placeholder="输入应用ID" allow-clear />
				</a-form-item>
				<a-form-item label="应用名称：">
					<a-input v-model:value="searchParams.appName" placeholder="输入应用名称" allow-clear />
				</a-form-item>
				<a-form-item label="创建者：">
					<a-input v-model:value="searchParams.userName" placeholder="输入创建者用户名" allow-clear />
				</a-form-item>
				<a-form-item label="生成类型：">
					<a-select v-model:value="searchParams.codeGenType" placeholder="选择生成类型" allow-clear>
						<a-select-option value="">全部</a-select-option>
						<a-select-option v-for="option in codeGenTypeOptions" :key="option.value" :value="option.value">
							{{ option.label }}
						</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item>
					<a-space>
						<a-button type="primary" html-type="submit" :loading="loading"> 搜索 </a-button>
						<a-button @click="resetSearch"> 重置 </a-button>
					</a-space>
				</a-form-item>
			</a-form>
		</div>

		<!-- 应用列表表格 -->
		<div class="table-section">
			<a-table
				:columns="columns"
				:data-source="dataList"
				:pagination="pagination"
				:loading="loading"
				@change="handleTableChange"
				:scroll="{ x: false }"
				size="middle"
				class="app-table"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'id'">
						<div class="id-cell">
							<span class="app-id">{{ record.id }}</span>
						</div>
					</template>

					<template v-else-if="column.dataIndex === 'appName'">
						<div class="app-name-cell">
							<span class="app-name">{{ record.appName || '未命名应用' }}</span>
						</div>
					</template>

					<template v-else-if="column.dataIndex === 'cover'">
						<div class="cover-cell">
							<img 
								v-if="record.cover" 
								:src="record.cover" 
								alt="封面" 
								class="app-cover" 
								@click="showImagePreview(record.cover)"
							/>
							<div v-else class="cover-placeholder">
								<AppstoreOutlined />
							</div>
						</div>
					</template>

					<template v-else-if="column.dataIndex === 'initPrompt'">
						<div class="prompt-cell">
							<span class="prompt-text">{{ record.initPrompt || '-' }}</span>
						</div>
					</template>

					<template v-else-if="column.dataIndex === 'codeGenType'">
						<a-tag :color="getCodeGenTypeColor(record.codeGenType)" class="type-tag">
							{{ getCodeGenTypeText(record.codeGenType) }}
						</a-tag>
					</template>

					<template v-else-if="column.dataIndex === 'priority'">
						<div class="priority-cell">
							<a-tag v-if="record.priority >= 99" color="gold" class="featured-tag"> 精选 </a-tag>
							<span v-else class="priority-number">{{ record.priority || 0 }}</span>
						</div>
					</template>

					<template v-else-if="column.dataIndex === 'deployedTime'">
						<div class="deploy-time-cell">
							<span v-if="record.deployedTime" class="deployed-time">
								{{ formatTime(record.deployedTime) }}
							</span>
							<span v-else class="not-deployed">未部署</span>
						</div>
					</template>

					<template v-else-if="column.dataIndex === 'userId'">
						<div class="user-cell" v-if="record.user">
							<a-avatar :size="24" :src="record.user.userAvatar" class="admin-app-user-avatar">
								{{ record.user.userName?.[0]?.toUpperCase() }}
							</a-avatar>
							<span class="user-name">{{ record.user.userName }}</span>
						</div>
						<span v-else class="no-user">未知用户</span>
					</template>

					<template v-else-if="column.dataIndex === 'createTime'">
						<div class="time-cell">
							{{ formatTime(record.createTime) }}
						</div>
					</template>

					<template v-else-if="column.key === 'actions'">
						<a-space class="action-buttons">
							<a-button type="link" size="small" @click="editApp(record.id)" class="action-btn edit-btn">
								编辑
							</a-button>
							<a-button type="link" size="small" @click="toggleFeatured(record)" class="action-btn featured-btn">
								{{ record.priority >= 99 ? '取消精选' : '精选' }}
							</a-button>
							<a-button type="link" size="small" danger @click="deleteApp(record.id)" class="action-btn delete-btn">
								删除
							</a-button>
						</a-space>
					</template>
				</template>
			</a-table>

			<!-- 分页信息 -->
			<div class="pagination-info">
				<span>共 {{ pagination.total }} 条</span>
			</div>
		</div>
	</div>

	<!-- 图片预览模态框 -->
	<a-modal
		v-model:open="previewVisible"
		:footer="null"
		:width="800"
		:centered="true"
		@cancel="handlePreviewCancel"
		class="image-preview-modal"
	>
		<template #title>
			<span>封面预览</span>
		</template>
		<div class="preview-image-container">
			<img :src="previewImage" alt="封面预览" class="preview-image" />
		</div>
	</a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { listAppVoByPageByAdmin, deleteAppByAdmin, updateAppByAdmin } from '@/api/appController'
import { AppstoreOutlined } from '@ant-design/icons-vue'
import { getCodeGenTypeOptions, getCodeGenTypeText, getCodeGenTypeColor } from '@/constants/codeGenType'
import dayjs from 'dayjs'

const router = useRouter()

// 生成类型选项
const codeGenTypeOptions = getCodeGenTypeOptions()

// 搜索参数
const searchParams = reactive({
	id: undefined as number | undefined,
	appName: '',
	codeGenType: '',
	priority: undefined as number | undefined,
	userName: undefined as string | undefined,
	sortField: undefined as string | undefined,
	sortOrder: undefined as string | undefined,
})

// 表格数据
const dataList = ref<API.AppVO[]>([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
	current: 1,
	pageSize: 10,
	total: 0,
	showSizeChanger: true,
	showQuickJumper: false,
	pageSizeOptions: ['10', '20', '50'],
	showTotal: (total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
})

// 选中行
const selectedRowKeys = ref<number[]>([])
const rowSelection = {
	selectedRowKeys,
	onChange: (keys: number[]) => {
		selectedRowKeys.value = keys
	},
}

// 图片预览相关
const previewVisible = ref(false)
const previewImage = ref('')

/**
 * 显示图片预览
 * @param imageUrl 图片URL
 */
const showImagePreview = (imageUrl: string) => {
	previewImage.value = imageUrl
	previewVisible.value = true
}

/**
 * 关闭图片预览
 */
const handlePreviewCancel = () => {
	previewVisible.value = false
	previewImage.value = ''
}

// 表格列配置
const columns = [
	{
		title: 'ID',
		dataIndex: 'id',
		width: 120,
		sorter: true,
	},
	{
		title: '应用名称',
		dataIndex: 'appName',
		width: 85,
	},
	{
		title: '封面',
		dataIndex: 'cover',
		width: 55,
	},
	{
		title: '初始提示词',
		dataIndex: 'initPrompt',
		width: 120,
	},
	{
		title: '生成类型',
		dataIndex: 'codeGenType',
		width: 85,
	},
	{
		title: '优先级',
		dataIndex: 'priority',
		width: 55,
		sorter: true,
	},
	{
		title: '部署时间',
		dataIndex: 'deployedTime',
		width: 110,
		sorter: true,
	},
	{
		title: '创建者',
		dataIndex: 'userId',
		width: 80,
	},
	{
		title: '创建时间',
		dataIndex: 'createTime',
		width: 105,
		sorter: true,
	},
	{
		title: '操作',
		key: 'actions',
		width: 140,
		fixed: 'right' as const,
	},
]

// 加载应用列表
const loadApps = async () => {
	loading.value = true
	try {
		const queryParams: API.AppQueryRequest = {
			current: pagination.current,
			pageSize: pagination.pageSize,
		}

		// 只添加非空的搜索参数
		if (searchParams.id) {
			queryParams.id = searchParams.id
		}
		if (searchParams.appName && searchParams.appName.trim()) {
			queryParams.appName = searchParams.appName.trim()
		}
		if (searchParams.codeGenType && searchParams.codeGenType.trim()) {
			queryParams.codeGenType = searchParams.codeGenType.trim()
		}
		if (searchParams.priority !== undefined && searchParams.priority !== null) {
			queryParams.priority = searchParams.priority
		}
		if (searchParams.userName && searchParams.userName.trim()) {
			queryParams.userName = searchParams.userName.trim()
		}
		if (searchParams.sortField && searchParams.sortOrder) {
			queryParams.sortField = searchParams.sortField
			queryParams.sortOrder = searchParams.sortOrder
		}

		const res = await listAppVoByPageByAdmin(queryParams)
		if (res.data.code === 0 && res.data.data) {
			dataList.value = res.data.data.records || []
			pagination.total = Number(res.data.data.totalRow) || 0
		} else {
			message.error('获取应用列表失败：' + (res.data.message || '未知错误'))
		}
	} catch (error) {
		console.error('加载应用列表失败:', error)
		message.error('获取应用列表失败，请稍后重试')
	} finally {
		loading.value = false
	}
}

// 搜索
const doSearch = () => {
	pagination.current = 1
	loadApps()
}

// 重置搜索
const resetSearch = () => {
	// 重置所有搜索参数
	searchParams.id = undefined
	searchParams.appName = ''
	searchParams.codeGenType = ''
	searchParams.priority = undefined
	searchParams.userName = undefined
	searchParams.sortField = undefined
	searchParams.sortOrder = undefined
	pagination.current = 1
	loadApps()
}

// 表格变化处理
const handleTableChange = (pag: any, filters: any, sorter: any) => {
	pagination.current = pag.current
	pagination.pageSize = pag.pageSize

	// 存储排序信息
	if (sorter.field && sorter.order) {
		searchParams.sortField = sorter.field
		searchParams.sortOrder = sorter.order === 'ascend' ? 'asc' : 'desc'
	} else {
		searchParams.sortField = undefined
		searchParams.sortOrder = undefined
	}

	loadApps()
}

// 编辑应用
const editApp = (appId: string | number) => {
	router.push(`/app/edit/${appId}`)
}

// 切换精选状态
const toggleFeatured = async (app: API.AppVO) => {
	if (!app.id) return

	const newPriority = app.priority && app.priority >= 99 ? 0 : 99
	const action = newPriority >= 99 ? '设为精选' : '取消精选'

	try {
		const res = await updateAppByAdmin({
			id: app.id,
			priority: newPriority,
		})

		if (res.data.code === 0) {
			message.success(`${action}成功`)
			loadApps()
		} else {
			message.error(`${action}失败：` + (res.data.message || '未知错误'))
		}
	} catch (error) {
		console.error(`${action}失败:`, error)
		message.error(`${action}失败，请稍后重试`)
	}
}

// 删除应用
const deleteApp = (appId: string | number) => {
	Modal.confirm({
		title: '确认删除',
		content: '删除应用后将无法恢复，确定要删除吗？',
		okText: '确认删除',
		cancelText: '取消',
		okType: 'danger',
		onOk: async () => {
			// 显示全局加载状态
			const hideLoading = message.loading('正在删除应用...', 0)
			
			try {
				const res = await deleteAppByAdmin({ id: appId as any })
				hideLoading()
				
				if (res.data.code === 0) {
					message.success('删除成功')
					loadApps()
				} else {
					message.error('删除失败：' + (res.data.message || '未知错误'))
				}
			} catch (error) {
				hideLoading()
				console.error('删除失败:', error)
				message.error('删除失败，请稍后重试')
			}
		},
	})
}

// 格式化时间
const formatTime = (time: string | undefined) => {
	if (!time) return ''
	return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 组件挂载时加载数据
onMounted(() => {
	loadApps()
})
</script>

<style scoped lang="scss">
#app-manage-view {
	background: #f8f9fa;
	height: 100%;
	max-width: 100%;
	overflow-x: hidden;

	.search-section {
		background: white;
		padding: 20px 24px;
		margin-bottom: 0;
		border-radius: 8px 8px 0 0;
		border: 1px solid #e8e8e8;
		border-bottom: none;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

		.search-form {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			gap: 16px;

			:deep(.ant-form-item) {
				margin-bottom: 0;
				margin-right: 0;
				display: flex;
				align-items: center;

				.ant-form-item-label {
					padding-right: 8px;
					width: auto;
					flex-shrink: 0;

					label {
						color: #333;
						font-size: 14px;
						font-weight: normal;
						margin-bottom: 0;
					}
				}

				.ant-form-item-control {
					min-height: auto;
				}
			}

			:deep(.ant-btn) {
				height: 32px;
				font-size: 14px;
				padding: 0 15px;
			}

			// 应用名称输入框
			:deep(.ant-form-item:nth-child(1) .ant-input) {
				width: 200px;
				height: 16px;
				align-items: center;
			}

			// 创建者输入框
			:deep(.ant-form-item:nth-child(2) .ant-input) {
				width: 200px;
				height: 16px;
				align-items: center;
			}

			// 生成类型选择框
		:deep(.ant-form-item:nth-child(4) .ant-select) {
			width: 180px;

				.ant-select-selector {
					height: 32px;
					font-size: 14px;

					.ant-select-selection-item {
						line-height: 30px;
					}

					.ant-select-selection-placeholder {
						line-height: 30px;
					}
				}
			}
		}
	}

	.table-section {
		background: white;
		border-radius: 0 0 8px 8px;
		border: 1px solid #e8e8e8;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
		overflow: hidden;

		.app-table {
			:deep(.ant-table) {
				font-size: 14px;

				.ant-table-thead > tr > th {
					background: #fafafa;
					color: #262626;
					font-weight: 500;
					border-bottom: 1px solid #e8e8e8;
					font-size: 14px;
					padding: 12px 8px;
					text-align: center;
				}

				.ant-table-tbody > tr > td {
					padding: 12px 8px;
					border-bottom: 1px solid #f0f0f0;
					font-size: 14px;
					vertical-align: middle; /* 垂直居中对齐 */
					text-align: center;
				}

				.ant-table-tbody > tr:hover > td {
					background: #f5f5f5;
				}
			}

			:deep(.ant-pagination) {
				margin: 16px;
				text-align: right;
			}
		}

		.id-cell {
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			z-index: 5;
		}

		.app-id {
			font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
			color: #1890ff;
			font-weight: 600;
			font-size: 13px;
			background: #f0f8ff;
			padding: 4px 8px;
			border-radius: 4px;
			display: inline-block;
			position: relative;
			z-index: 10;
			white-space: nowrap;
			overflow: visible;
		}

		.app-name-cell {
			text-align: center !important;
			max-width: 140px;
			padding: 8px !important;

			.app-name {
				font-weight: 500;
				color: #333;
				font-size: 14px;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				line-clamp: 2;
				-webkit-box-orient: vertical;
				overflow: hidden;
				text-overflow: ellipsis;
				line-height: 1.4;
				word-break: break-word;
				max-height: 2.8em; /* 约2行的高度 */
				text-align: center;
			}
		}

		.cover-cell {
			display: flex;
			align-items: center;
			justify-content: center;

			.app-cover {
			width: 40px;
			height: 40px;
			object-fit: cover;
			border-radius: 4px;
			border: 1px solid #e8e8e8;
			cursor: pointer;
			transition: all 0.3s ease;

			&:hover {
				transform: scale(1.1);
				box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
			}
		}

			.cover-placeholder {
				width: 40px;
				height: 40px;
				display: flex;
				align-items: center;
				justify-content: center;
				background: #f5f5f5;
				border-radius: 4px;
				border: 1px solid #e8e8e8;
				color: #999;
				font-size: 16px;
			}
		}

		.prompt-cell {
			display: flex;
			align-items: center;
			justify-content: center;
			max-width: 180px;
			padding: 8px !important;

			.prompt-text {
				display: inline-block;
				max-width: 160px;
				color: #666;
				font-size: 13px;
				line-height: 1.4;
				word-break: break-word;
				text-align: center;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				line-clamp: 2;
				-webkit-box-orient: vertical;
				max-height: 2.8em;
			}
		}

		.type-tag {
			font-size: 12px;
			border-radius: 2px;
			margin: 0;
		}

		.priority-cell {
			.featured-tag {
				font-weight: 500;
				font-size: 12px;
			}

			.priority-number {
				color: #666;
				font-size: 14px;
			}
		}

		.deploy-time-cell {
			font-size: 13px;
			text-align: center;

			.deployed-time {
				color: #52c41a;
				font-weight: 500;
			}

			.not-deployed {
				color: #999;
			}
		}

		.user-cell {
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 6px;
			text-align: center !important;

			.user-avatar {
				flex-shrink: 0;
				font-size: 12px;
			}

			.user-name {
				color: #333;
				font-size: 13px;
				max-width: 80px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}

		.no-user {
			color: #999;
			font-size: 13px;
		}

		.time-cell {
			color: #666;
			font-size: 13px;
			white-space: nowrap;
		}

		.action-buttons {
			:deep(.ant-space-item) {
				.action-btn {
					padding: 4px 8px;
					height: auto;
					font-size: 12px;
					line-height: 1.4;
					border-radius: 4px;

					&.edit-btn {
						background: #52c41a;
						color: white;
						border: 1px solid #ff8c00;

						&:hover {
							background: #73d13d;
							border-color: #73d13d;
						}
					}

					&.featured-btn {
						background: #faad14;
						color: white;
						border: 1px solid #faad14;

						&:hover {
							background: #ffc53d;
							border-color: #ffc53d;
						}
					}

					&.delete-btn {
						background: #ff4d4f;
						color: white;
						border: 1px solid #ff4d4f;

						&:hover {
							background: #ff7875;
							border-color: #ff7875;
						}
					}
				}
			}
		}

		.pagination-info {
			padding: 12px 16px;
			text-align: left;
			color: #666;
			font-size: 14px;
			border-top: 1px solid #f0f0f0;
			background: #fafafa;
		}
	}
}

// 图片预览模态框样式
.image-preview-modal {
	:deep(.ant-modal-content) {
		padding: 0;
		overflow: hidden;
	}

	:deep(.ant-modal-header) {
		padding: 16px 24px;
		border-bottom: 1px solid #f0f0f0;
	}

	:deep(.ant-modal-body) {
		padding: 0;
	}

	.preview-image-container {
		display: flex;
		justify-content: center;
		align-items: center;
		background: #f5f5f5;
		min-height: 400px;

		.preview-image {
			max-width: 100%;
			max-height: 600px;
			object-fit: contain;
			border-radius: 4px;
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
		}
	}
}

// 响应式设计
@media (max-width: 1400px) {
	#app-manage-view {
		.table-section {
			.app-table {
				:deep(.ant-table) {
					.ant-table-thead > tr > th,
					.ant-table-tbody > tr > td {
						padding: 8px 6px;
						font-size: 13px;
						min-height: 50px;
					}
				}
			}

			.app-name-cell {
				max-width: 120px;
			}

			.prompt-cell {
				max-width: 150px;
			}

			.action-buttons {
				:deep(.ant-space-item) {
					.action-btn {
						padding: 2px 6px;
						font-size: 11px;
					}
				}
			}
		}
	}
}

@media (max-width: 1200px) {
	#app-manage-view {
		.table-section {
			.app-name-cell {
				max-width: 100px;
			}

			.prompt-cell {
				max-width: 120px;
			}
		}
	}
}

.admin-app-user-avatar {
	border: 2px solid #ff8c00 !important;
	box-shadow: 0 2px 8px rgba(255, 140, 0, 0.3) !important;
	transition: all 0.3s ease !important;
	
	&:hover {
		border-color: #ff7700 !important;
		box-shadow: 0 4px 12px rgba(255, 140, 0, 0.4) !important;
		transform: translateY(-1px) !important;
	}
}
</style>
